package co.edu.usbcali.unidad.presentation.backEndBeans;

import co.edu.usbcali.unidad.exceptions.*;
import co.edu.usbcali.unidad.modelo.*;
import co.edu.usbcali.unidad.modelo.dto.CorrespondenciaDTO;
import co.edu.usbcali.unidad.presentation.businessDelegate.BusinessDelegatorView;
import co.edu.usbcali.unidad.utilities.*;

import com.icesoft.faces.async.render.RenderManager;
import com.icesoft.faces.async.render.Renderable;
import com.icesoft.faces.component.ext.HtmlCommandButton;
import com.icesoft.faces.component.ext.HtmlInputText;
import com.icesoft.faces.component.ext.HtmlSelectOneMenu;
import com.icesoft.faces.component.selectinputdate.SelectInputDate;
import com.icesoft.faces.context.DisposableBean;
import com.icesoft.faces.webapp.xmlhttp.FatalRenderingException;
import com.icesoft.faces.webapp.xmlhttp.PersistentFacesState;
import com.icesoft.faces.webapp.xmlhttp.RenderingException;
import com.icesoft.faces.webapp.xmlhttp.TransientRenderingException;

import java.math.BigDecimal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;
import java.util.Vector;

import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;
import javax.faces.model.SelectItem;

public class CorrespondenciaView extends DataSource implements Renderable,
		DisposableBean {
	private HtmlInputText txtCorAsunto;
	private HtmlSelectOneMenu cmbTipoCorrespondencia;
	private HtmlInputText txtCorCodigo;
	private HtmlCommandButton btnSave;
	private HtmlCommandButton btnModify;
	private HtmlCommandButton btnDelete;
	private HtmlCommandButton btnClear;
	private boolean renderDataTable;
	private boolean flag = true;
	private RenderManager renderManager;
	private PersistentFacesState state = PersistentFacesState.getInstance();
	private List<Correspondencia> correspondencia;
	private List<CorrespondenciaDTO> correspondenciaDTO;
	private List<SelectItem> listTipoCorrespondencia = new ArrayList<SelectItem>();

	public CorrespondenciaView() {
		super("");
	}

	public HtmlSelectOneMenu getCmbTipoCorrespondencia() {
		try {
			List<TipoCorrespondencia> list = BusinessDelegatorView
					.findByCriteriaInTipoCorrespondencia(null, null, null);
			listTipoCorrespondencia.clear();
			listTipoCorrespondencia.add(new SelectItem(0,
					"Seleccione Tipo Correspondencia"));

			for (TipoCorrespondencia tipoCorrespondencia : list) {
				listTipoCorrespondencia.add(new SelectItem(tipoCorrespondencia
						.getTpcCodigo(), tipoCorrespondencia.getTpcNombre()));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return cmbTipoCorrespondencia;
	}

	public void setCmbTipoCorrespondencia(
			HtmlSelectOneMenu cmbTipoCorrespondencia) {
		this.cmbTipoCorrespondencia = cmbTipoCorrespondencia;
	}

	public List<SelectItem> getListTipoCorrespondencia() {
		return listTipoCorrespondencia;
	}

	public void setListTipoCorrespondencia(
			List<SelectItem> listTipoCorrespondencia) {
		this.listTipoCorrespondencia = listTipoCorrespondencia;
	}

	public String action_clear() {
		txtCorAsunto.setValue(null);
		txtCorAsunto.setDisabled(true);
		cmbTipoCorrespondencia.setValue(null);
		cmbTipoCorrespondencia.setDisabled(true);
		txtCorCodigo.setValue(null);
		txtCorCodigo.setDisabled(false);
		btnSave.setDisabled(true);
		btnDelete.setDisabled(true);
		btnModify.setDisabled(true);
		btnClear.setDisabled(false);

		return "";
	}

	public void listener_txtId(ValueChangeEvent event) {
		if ((event.getNewValue() != null) && !event.getNewValue().equals("")) {
			Correspondencia entity = null;

			try {
				String corCodigo = new String(txtCorCodigo.getValue()
						.toString());
				entity = BusinessDelegatorView.getCorrespondencia(corCodigo);
			} catch (Exception e) {
				// TODO: handle exception
			}

			if (entity == null) {
				txtCorAsunto.setDisabled(false);
				cmbTipoCorrespondencia.setDisabled(false);
				txtCorCodigo.setDisabled(false);
				btnSave.setDisabled(false);
				btnDelete.setDisabled(true);
				btnModify.setDisabled(true);
				btnClear.setDisabled(false);
			} else {
				txtCorAsunto.setValue(entity.getCorAsunto());
				txtCorAsunto.setDisabled(false);
				cmbTipoCorrespondencia.setValue(entity.getTipoCorrespondencia()
						.getTpcCodigo());
				cmbTipoCorrespondencia.setDisabled(false);
				txtCorCodigo.setValue(entity.getCorCodigo());
				txtCorCodigo.setDisabled(true);
				btnSave.setDisabled(true);
				btnDelete.setDisabled(false);
				btnModify.setDisabled(false);
				btnClear.setDisabled(false);
			}
		}
	}

	public String action_save() {
		try {

			String asunto = txtCorAsunto.getValue().toString();
			String coCodigo = txtCorCodigo.getValue().toString();
			String tipoCorres = cmbTipoCorrespondencia.getValue().toString();

			if (asunto.trim().equals("")) {
				throw new Exception( "Es necesario conocer el asunto de esta correspondencia");
			}

			if (!Utilities.soloNumeros(coCodigo)) {
				throw new Exception( "El codigo debe ser numerico");
			}
			
			if (coCodigo.trim().equals("")) {
				throw new Exception("El codigo es obligatorio");
			}

			if (tipoCorres.trim().equals("")) {
				throw new Exception("Debe elejir una opcion");
			}

			BusinessDelegatorView.saveCorrespondencia(asunto, coCodigo,
					tipoCorres);
			FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYSAVED);
			action_clear();
		} catch (Exception e) {
			FacesUtils.addErrorMessage(e.getMessage());
		}

		return "";
	}

	public String action_delete() {
		try {
			BusinessDelegatorView.deleteCorrespondencia(FacesUtils
					.checkString(txtCorCodigo));
			FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYDELETED);
			action_clear();
		} catch (Exception e) {
			FacesUtils.addErrorMessage(e.getMessage());
		}

		return "";
	}

	public String action_modify() {
		try {
			String asunto = txtCorAsunto.getValue().toString();
			String coCodigo = txtCorCodigo.getValue().toString();
			String tipoCorres = cmbTipoCorrespondencia.getValue().toString();

			if (asunto.trim().equals("")) {
				throw new Exception(
						"Es necesario conocer el asunto de esta correspondencia");
			}

			if (!Utilities.soloNumerosyLetras(coCodigo)) {
				throw new Exception(
						"El codigo no debe contener caracteres especiales");
			}

			if (tipoCorres.trim().equals("")) {
				throw new Exception("Debe elejir una opcion");
			}
			BusinessDelegatorView.updateCorrespondencia(asunto, coCodigo,
					tipoCorres);
			FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYMODIFIED);
			action_clear();
		} catch (Exception e) {
			FacesUtils.addErrorMessage(e.getMessage());
		}

		return "";
	}

	public String action_modifyWitDTO(String corAsunto, String corCodigo,
			String tpcCodigo_TipoCorrespondencia) throws Exception {
		try {
			BusinessDelegatorView.updateCorrespondencia(corAsunto, corCodigo,
					tpcCodigo_TipoCorrespondencia);
			renderManager.getOnDemandRenderer("CorrespondenciaView")
					.requestRender();
			FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYMODIFIED);
		} catch (Exception e) {
			// renderManager.getOnDemandRenderer("CorrespondenciaView").requestRender();
			FacesUtils.addErrorMessage(e.getMessage());
			throw e;
		}

		return "";
	}

	public List<Correspondencia> getCorrespondencia() {
		if (flag) {
			try {
				correspondencia = BusinessDelegatorView.getCorrespondencia();
				flag = false;
			} catch (Exception e) {
				flag = true;
				FacesUtils.addErrorMessage(e.getMessage());
			}
		}

		return correspondencia;
	}

	public boolean isFlag() {
		return flag;
	}

	public void setCorrespondencia(List<Correspondencia> correspondencia) {
		this.correspondencia = correspondencia;
	}

	public boolean isRenderDataTable() {
		try {
			if (flag) {
				if (BusinessDelegatorView.findTotalNumberCorrespondencia() > 0) {
					renderDataTable = true;
				} else {
					renderDataTable = false;
				}
			}

			flag = false;
		} catch (Exception e) {
			renderDataTable = false;
			e.printStackTrace();
		}

		return renderDataTable;
	}

	public DataModel getData() {
		state = PersistentFacesState.getInstance();

		if (onePageDataModel == null) {
			onePageDataModel = new LocalDataModel(pageSize);
		}

		return onePageDataModel;
	}

	/**
	 * This is where the Object data is retrieved from the database and returned
	 * as a list of objects for display in the UI.
	 */
	private DataPage<Correspondencia> getDataPage(int startRow, int pageSize) {
		// Retrieve the total number of objects from the database. This
		// number is required by the DataPage object so the paginator will know
		// the relative location of the page data.
		int totalNumberCorrespondencia = 0;

		try {
			totalNumberCorrespondencia = BusinessDelegatorView
					.findTotalNumberCorrespondencia().intValue();
		} catch (Exception e) {
			FacesUtils.addErrorMessage(e.getMessage());
		}

		// Calculate indices to be displayed in the ui.
		int endIndex = startRow + pageSize;

		if (endIndex > totalNumberCorrespondencia) {
			endIndex = totalNumberCorrespondencia;
		}

		try {
			correspondencia = BusinessDelegatorView.findPageCorrespondencia(
					sortColumnName, sortAscending, startRow, endIndex
							- startRow);

			// Remove this Renderable from the existing render groups.
			// leaveRenderGroups();
		} catch (Exception e) {
			FacesUtils.addErrorMessage(e.getMessage());
		}

		// Add this Renderable to the new render groups.
		// joinRenderGroups();
		// Reset the dirtyData flag.
		onePageDataModel.setDirtyData(false);
		// This is required when using Hibernate. If the SessionManager is not
		// cleared or closed objects are cached and stale objects will show up
		// in the table.
		// This way, the detached objects are reread from the database.
		// This call is not required with Hibernate, which uses a Query Hint
		// to clear the l2 cache in the DAO.
		flag = true;

		return new DataPage<Correspondencia>(totalNumberCorrespondencia,
				startRow, correspondencia);
	}

	public DataModel getDataDTO() {
		state = PersistentFacesState.getInstance();

		if (onePageDataModel == null) {
			onePageDataModel = new LocalDataModelDTO(pageSize);
		}

		return onePageDataModel;
	}

	/**
	 * This is where the Object data is retrieved from the database and returned
	 * as a list of objects for display in the UI.
	 */
	private DataPage<CorrespondenciaDTO> getDataPageDTO(int startRow,
			int pageSize) {
		// Retrieve the total number of objects from the database. This
		// number is required by the DataPage object so the paginator will know
		// the relative location of the page data.
		int totalNumberCorrespondencia = 0;

		try {
			totalNumberCorrespondencia = BusinessDelegatorView
					.findTotalNumberCorrespondencia().intValue();
		} catch (Exception e) {
			FacesUtils.addErrorMessage(e.getMessage());
		}

		// Calculate indices to be displayed in the ui.
		int endIndex = startRow + pageSize;

		if (endIndex > totalNumberCorrespondencia) {
			endIndex = totalNumberCorrespondencia;
		}

		try {
			correspondencia = BusinessDelegatorView.findPageCorrespondencia(
					sortColumnName, sortAscending, startRow, endIndex
							- startRow);

			if (Utilities.validationsList(correspondencia)) {
				correspondenciaDTO = new ArrayList<CorrespondenciaDTO>();

				for (Correspondencia correspondenciaTmp : correspondencia) {
					CorrespondenciaDTO correspondenciaDTO2 = new CorrespondenciaDTO();
					correspondenciaDTO2.setCorCodigo(correspondenciaTmp
							.getCorCodigo().toString());
					correspondenciaDTO2.setCorAsunto((correspondenciaTmp
							.getCorAsunto() != null) ? correspondenciaTmp
							.getCorAsunto().toString() : null);
					correspondenciaDTO2
							.setTpcCodigo_TipoCorrespondencia((correspondenciaTmp
									.getTipoCorrespondencia().getTpcCodigo() != null) ? correspondenciaTmp
									.getTipoCorrespondencia().getTpcCodigo()
									.toString()
									: null);
					correspondenciaDTO2.setCorrespondencia(correspondenciaTmp);
					correspondenciaDTO2.setCorrespondenciaView(this);
					correspondenciaDTO.add(correspondenciaDTO2);
				}
			}

			// Remove this Renderable from the existing render groups.
			leaveRenderGroups();
		} catch (Exception e) {
			FacesUtils.addErrorMessage(e.getMessage());
		}

		// Add this Renderable to the new render groups.
		joinRenderGroups();
		// Reset the dirtyData flag.
		onePageDataModel.setDirtyData(false);
		// This is required when using Hibernate. If the SessionManager is not
		// cleared or closed objects are cached and stale objects will show up
		// in the table.
		// This way, the detached objects are reread from the database.
		// This call is not required with Hibernate, which uses a Query Hint
		// to clear the l2 cache in the DAO.
		flag = true;

		return new DataPage<CorrespondenciaDTO>(totalNumberCorrespondencia,
				startRow, correspondenciaDTO);
	}

	protected boolean isDefaultAscending(String sortColumn) {
		return true;
	}

	/**
	 * This method is called when a render call is made from the server. Render
	 * calls are only made to views containing an updated record. The data is
	 * marked as dirty to trigger a fetch of the updated record from the
	 * database before rendering takes place.
	 */
	public PersistentFacesState getState() {
		onePageDataModel.setDirtyData();

		return state;
	}

	/**
	 * This method is called from faces-config.xml with each new session.
	 */
	public void setRenderManager(RenderManager renderManager) {
		this.renderManager = renderManager;
	}

	public void renderingException(RenderingException arg0) {
		if (arg0 instanceof TransientRenderingException) {
		} else if (arg0 instanceof FatalRenderingException) {
			// Remove from existing Customer render groups.
			leaveRenderGroups();
		}
	}

	/**
	 * Remove this Renderable from existing uiCustomerBeans render groups.
	 * OnDemandRenderers are named/created using the underlying Customer Number.
	 */
	private void leaveRenderGroups() {
		if (Utilities.validationsList(correspondenciaDTO)) {
			for (CorrespondenciaDTO correspondenciaTmp : correspondenciaDTO) {
				renderManager.getOnDemandRenderer("CorrespondenciaView")
						.remove(this);
			}
		}
	}

	/**
	 * Add this Renderable to the new uiCustomerBeans render groups.
	 * OnDemandRenderers are named/created using the underlying Customer Number.
	 */
	private void joinRenderGroups() {
		if (Utilities.validationsList(correspondenciaDTO)) {
			for (CorrespondenciaDTO correspondenciaTmp : correspondenciaDTO) {
				renderManager.getOnDemandRenderer("CorrespondenciaView").add(
						this);
			}
		}
	}

	public void dispose() throws Exception {
	}

	public RenderManager getRenderManager() {
		return renderManager;
	}

	public void setState(PersistentFacesState state) {
		this.state = state;
	}

	public HtmlInputText getTxtCorAsunto() {
		return txtCorAsunto;
	}

	public void setTxtCorAsunto(HtmlInputText txtCorAsunto) {
		this.txtCorAsunto = txtCorAsunto;
	}

	public HtmlInputText getTxtCorCodigo() {
		return txtCorCodigo;
	}

	public void setTxtCorCodigo(HtmlInputText txtCorCodigo) {
		this.txtCorCodigo = txtCorCodigo;
	}

	public HtmlCommandButton getBtnSave() {
		return btnSave;
	}

	public void setBtnSave(HtmlCommandButton btnSave) {
		this.btnSave = btnSave;
	}

	public HtmlCommandButton getBtnModify() {
		return btnModify;
	}

	public void setBtnModify(HtmlCommandButton btnModify) {
		this.btnModify = btnModify;
	}

	public HtmlCommandButton getBtnDelete() {
		return btnDelete;
	}

	public void setBtnDelete(HtmlCommandButton btnDelete) {
		this.btnDelete = btnDelete;
	}

	public HtmlCommandButton getBtnClear() {
		return btnClear;
	}

	public void setBtnClear(HtmlCommandButton btnClear) {
		this.btnClear = btnClear;
	}

	public void setRenderDataTable(boolean renderDataTable) {
		this.renderDataTable = renderDataTable;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

	public List<CorrespondenciaDTO> getCorrespondenciaDTO() {
		return correspondenciaDTO;
	}

	public void setCorrespondenciaDTO(
			List<CorrespondenciaDTO> correspondenciaDTO) {
		this.correspondenciaDTO = correspondenciaDTO;
	}

	public TimeZone getTimeZone() {
		return java.util.TimeZone.getDefault();
	}

	/**
	 * A special type of JSF DataModel to allow a datatable and datapaginator to
	 * page through a large set of data without having to hold the entire set of
	 * data in memory at once. Any time a managed bean wants to avoid holding an
	 * entire dataset, the managed bean declares this inner class which extends
	 * PagedListDataModel and implements the fetchData method. fetchData is
	 * called as needed when the table requires data that isn't available in the
	 * current data page held by this object. This requires the managed bean
	 * (and in general the business method that the managed bean uses) to
	 * provide the data wrapped in a DataPage object that provides info on the
	 * full size of the dataset.
	 */
	private class LocalDataModel extends PagedListDataModel {
		public LocalDataModel(int pageSize) {
			super(pageSize);
		}

		public DataPage<Correspondencia> fetchPage(int startRow, int pageSize) {
			// call enclosing managed bean method to fetch the data
			return getDataPage(startRow, pageSize);
		}
	}

	private class LocalDataModelDTO extends PagedListDataModel {
		public LocalDataModelDTO(int pageSize) {
			super(pageSize);
		}

		public DataPage<CorrespondenciaDTO> fetchPage(int startRow, int pageSize) {
			// call enclosing managed bean method to fetch the data
			return getDataPageDTO(startRow, pageSize);
		}
	}
}
